<script lang="ts" setup>
import { type RouteLocationMatched, type RouteLocationRaw } from "vue-router"
import { compile } from "path-to-regexp"
import { useDisplay } from "vuetify"
import { VBreadcrumbs } from 'vuetify/components'
const { mobile } = useDisplay()

// 类型导出
// https://github.com/vuetifyjs/vuetify/issues/16680

// 直接复制过来的，引用不了 在 vuetify/lib/index.d.ts
// fuck!
// breadcumbItem
interface LinkProps {
    href: string | undefined;
    replace: boolean | undefined;
    to: RouteLocationRaw | undefined;
    exact: boolean | undefined;
}

type BreadcrumbItem = string | (LinkProps & {
    text: string;
    disabled?: boolean;
});

type MyVBreadcrumbsItem = Extract<
    VBreadcrumbs['$props']['items'],
    BreadcrumbItem[]
>


const route = useRoute()
const router = useRouter()

const breadcrumbs = ref<RouteLocationMatched[]>([])

const getBreadcrumb = () => {
    breadcrumbs.value = route.matched.filter((item) => !!(item?.meta!.title))
}

const pathCompile = (path: string) => {
    const { params } = route
    const toPath = compile(path)
    return toPath(params)
}

const handleLink = (item: RouteLocationMatched) => {
    const { redirect, path } = item
    if (redirect) {
        router.push(redirect as string)
        return
    }
    router.push(pathCompile(path))
}

//  监听路由改变
watch(() => route.path, (path: string) => {
    if (path.startsWith("/redirect/")) {
        return
    }
    getBreadcrumb()
}
)

getBreadcrumb()



const breadcrumbComputed = computed(() => {
    let o = [] as MyVBreadcrumbsItem[]
    let index = 0
    for (let i of breadcrumbs.value) {
        index++
        let item = { text: i?.meta!.title as string, href: i?.path, disabled: index === 2, to: i?.path, replace: false, exact: false } as MyVBreadcrumbsItem
        o.push(item)
    }
    return o
})

</script>
<template>
    <v-breadcrumbs :items="breadcrumbComputed">
        <template #title>
            {{ mobile }}
        </template>

        <template v-slot:item="{ item }">
            <v-breadcrumbs-item :to="item?.to" :disabled="item?.disabled">
            </v-breadcrumbs-item>
        </template>

    </v-breadcrumbs>
</template>


<style lang="scss" scoped></style>
